home *** CD-ROM | disk | FTP | other *** search
/ Reverse Code Engineering RCE CD +sandman 2000 / ReverseCodeEngineeringRceCdsandman2000.iso / RCE / Ebooks / Thinking in C++ V2 / C25 / InnerClassIdiom.cpp < prev    next >
Encoding:
C/C++ Source or Header  |  2000-05-25  |  1.5 KB  |  71 lines

  1. //: C25:InnerClassIdiom.cpp
  2. // From Thinking in C++, 2nd Edition
  3. // Available at http://www.BruceEckel.com
  4. // (c) Bruce Eckel 1999
  5. // Copyright notice in Copyright.txt
  6. // Example of the "inner class" idiom
  7. #include <iostream>
  8. #include <string>
  9. using namespace std;
  10.  
  11. class Poingable {
  12. public:
  13.   virtual void poing() = 0;
  14. };
  15.  
  16. void callPoing(Poingable& p) {
  17.   p.poing();
  18. }
  19.  
  20. class Bingable {
  21. public:
  22.   virtual void bing() = 0;
  23. };
  24.  
  25. void callBing(Bingable& b) {
  26.   b.bing();
  27. }
  28.  
  29. class Outer {
  30.   string name;
  31.   // Define one inner class:
  32.   class Inner1;
  33.   friend class Outer::Inner1;
  34.   class Inner1 : public Poingable {
  35.     Outer* parent;
  36.   public:
  37.     Inner1(Outer* p) : parent(p) {}
  38.     void poing() {
  39.       cout << "poing called for "
  40.         << parent->name << endl;
  41.       // Accesses data in the outer class object
  42.     }
  43.   } inner1;
  44.   // Define a second inner class:
  45.   class Inner2;
  46.   friend class Outer::Inner2;
  47.   class Inner2 : public Bingable {
  48.     Outer* parent;
  49.   public:
  50.     Inner2(Outer* p) : parent(p) {}
  51.     void bing() {
  52.       cout << "bing called for "
  53.         << parent->name << endl;
  54.     }
  55.   } inner2;
  56. public:
  57.   Outer(const string& nm) : name(nm), 
  58.     inner1(this), inner2(this) {}
  59.   // Return reference to interfaces
  60.   //  implemented by the inner classes:
  61.   operator Poingable&() { return inner1; }
  62.   operator Bingable&() { return inner2; }
  63. };
  64.  
  65. int main() {
  66.   Outer x("Ping Pong");
  67.   // Like upcasting to multiple base types!:
  68.   callPoing(x);
  69.   callBing(x);
  70. } ///:~
  71.